/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.pucp.Util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
 *
 * @author jorge
 */
public class Encriptador {  
    Cipher encrypt;
    Cipher decrypt;    
    String keyTxt;
    
    public Encriptador(){
        keyTxt = "4d89g13j4j91j27c582ji69373y788r6";
        try{
            encrypt = Cipher.getInstance("DES");
            decrypt = Cipher.getInstance("DES");
         
            KeySpec ks = new DESKeySpec(keyTxt.getBytes("UTF8"));
            SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
            SecretKey ky = kf.generateSecret(ks);
            encrypt.init(Cipher.ENCRYPT_MODE, ky);
            decrypt.init(Cipher.DECRYPT_MODE, ky);

        }catch(  InvalidKeySpecException | UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException ex){
        }
    }

    public String encriptar(String str){
        try {
            byte[] utf8 = str.getBytes("UTF8");
            byte[] enc = encrypt.doFinal(utf8);

            return Base64.encodeBase64String(enc);
        } catch (javax.crypto.BadPaddingException | IllegalBlockSizeException | java.io.IOException e) {
        }
        return null;
    }

    public String desencriptar(String str) {
        try {
            byte[] dec = Base64.decodeBase64(str);
            byte[] utf8 = decrypt.doFinal(dec);

            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException | IllegalBlockSizeException | java.io.IOException e) {
        }
        return null;
    }    
}
